<template>
  <div>
    <el-container>
      <el-header>
        <p>{{ listNames }}</p>
        <el-button type="primary" style="margin-left: 16px" @click="add">
          新增类目
        </el-button>
        <el-button type="primary" style="margin-left: 16px" @click="upload">
          上传图片
        </el-button>
      </el-header>
      <el-container>
        <el-aside>
          <div class="wrapper" :loading="loading">
            <div
              class="item"
              v-for="(item, index) in cateList"
              :key="item.id"
              :class="{ active: activeId == index }"
              @click="getImgList(item.id, item.name, index)"
            >
              <span>
                {{ item.name }}
              </span>
              <div class="btn">
                <el-button text @click="openEdit(item.name)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <el-button text @click="closeDelete(item.id)">
                  <el-icon>
                    <Close />
                  </el-icon>
                </el-button>
              </div>
            </div>
            <div class="pages">
              <el-pagination
                small
                background
                layout="prev, pager, next"
                :total="totals"
                :page-size="limit"
                :current-page="currentPage"
                @current-change="changePage"
              />
            </div>
          </div>
        </el-aside>
        <el-main>
          <div
            class="imgs"
            v-for="(item, index) in imgList"
            :key="item.id"
            :loading="loading"
          >
            <img :src="item.url" alt="" />
            <p>{{ item.name }}</p>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <Drawer ref="imagesDrawer" title="新增类目" size="30%" @submit="submitAdd">
      <el-form
        label-width="100px"
        :model="formAdd"
        :rules="rulesAdd"
        style="max-width: 460px"
        ref="formRefs"
      >
        <el-form-item label="Name" prop="textName">
          <el-input type="text" v-model="formAdd.textName" />
        </el-form-item>
        <el-form-item label="Order" prop="numberOrder">
          <el-input type="number" v-model="formAdd.numberOrder" />
        </el-form-item>
      </el-form>
    </Drawer>
    <Drawer
      ref="uploadDrawer"
      title="上传图片"
      size="45%"
      @submit="submitUpload"
    >
      <el-upload class="upload-demo" drag action="/api/admin/" multiple>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500kb
          </div>
        </template>
      </el-upload>
    </Drawer>
    <el-dialog
      v-model="visible"
      :close-on-click-modal="false"
      style="width: 35%"
    >
      <el-form
        label-width="100px"
        :model="formEdit"
        :rules="rules"
        style="max-width: 460px"
        ref="formEditRef"
      >
        <el-form-item label="旧名称：" prop="oldName">
          <el-input type="text" v-model="formEdit.oldName" />
        </el-form-item>
        <el-form-item label="重命名：" prop="newName">
          <el-input type="text" v-model="formEdit.newName" />
        </el-form-item>
      </el-form>
      <div class="nameBtn">
        <el-button type="primary" @click="getChangeCate(), closeEdit()"
          >提交</el-button
        >
        <el-button type="primary" @click="closeEdit">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import Drawer from "./Drawer.vue";
import { reactive, ref } from "vue";
import {
  imageCateList,
  imageDeleteList,
  imageAddList,
  imageList,
  imageChangeList,
  uploadImg,
} from "@/api/images.js";
import { open, toast } from "@/utils/index.js";

// 新增类目校验
const formRefs = ref(null);
const formAdd = reactive({
  textName: "",
  numberOrder: "",
});
const rulesAdd = reactive({
  textName: [
    {
      required: true,
      message: "名称必填哦！",
      trigger: "blur",
    },
  ],
  numberOrder: [
    {
      required: true,
      message: "空着不太好吧！",
      trigger: "blur",
    },
  ],
});

// 修改类目校验
const formEditRef = ref(null);
const formEdit = reactive({
  oldName: "",
  newName: "",
});
const rules = reactive({
  oldName: [
    {
      required: true,
      message: "输入欲修改的名称",
      trigger: "blur",
    },
  ],
  newName: [
    {
      required: true,
      message: "输入设想好的新名称",
      trigger: "blur",
    },
  ],
});

const visible = ref(false);

const imagesDrawer = ref(null);
const uploadDrawer = ref(null);

// 图库数组
const imgList = ref([]);

const activeId = ref(0);
const cateList = ref([]);
//总条数
const totals = ref(0);
//当前页
const currentPage = ref(1);
//一页显示多少条
const limit = ref(10);

const loading = ref(false);

const changePage = (pageNum) => {
  getCateListData(pageNum);
  //   console.log(pageNum);
};

//获取类目分类数据
function getCateListData(page) {
  loading.value = true;
  imageCateList(page)
    .then((res) => {
      console.log(res);
      cateList.value = res.list;
      totals.value = res.totalCount;
      currentPage.value = page;
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      loading.value = false;
    });
}
getCateListData();
// 提交新增类目
const submitAdd = () => {
  formRefs.value.validate(() => {
    if (formAdd.textName !== null && formAdd.numberOrder !== null) {
      imageAddList(formAdd.textName, Number(formAdd.numberOrder))
        .then((res) => {
          toast("成功添加！");
        })
        .catch((err) => {
          toast("添加失败！");
        });
    } else {
      toast("类目名称或order不能为空");
    }
  });
};

// 修改类目
function getChangeCate() {
  formEditRef.value
    .validate()
    .then((res) => {
      const index = cateList.value.findIndex((item) => {
        return item.name === formEdit.oldName;
      });
      console.log(index);
      if (index !== -1) {
        imageChangeList(cateList.value[index].id, formEdit.newName)
          .then((res) => {
            cateList.value[index].name = formEdit.newName;
            toast("类目修改成功");
          })
          .catch((err) => {
            toast("类目修改失败,稍后重试");
          });
      }
    })
    .catch((err) => {});
}

// 删除类目
function closeDelete(deleId) {
  open("确定要删除此类目嘛？")
    .then(() => {
      imageDeleteList(deleId).then(() => {
        let indexDel = cateList.value.findIndex((item) => {
          return item.id === deleId;
        });
        if (indexDel !== -1) {
          cateList.value.splice(indexDel, 1);
        }
        console.log(deleId);
      });
    })
    .catch(() => {
      toast("删除操作取消成功！");
    });
}

const listNames = ref("");
// 图库列表
function getImgList(ImgId, listName, index) {
  listNames.value = listName;
  activeId.value = index;
  imageList(ImgId)
    .then((res) => {
      console.log(res);
      imgList.value = res.list;
    })
    .catch((err) => {
      console.log(err);
    });
}
getImgList();

//提交上传图片
const submitUpload = () => {
  // uploadImg()
  //   .then((res) => {
  //     // console.log("提交上传成功");
  //     console.log(res);
  //     toast("上传成功");
  //   })
  //   .catch((err) => {
  //     toast("上传失败" , "error");
  //   });
};
//打开修改框
function openEdit(changeName) {
  visible.value = true;
  formEdit.oldName = changeName;
}
// 关闭修改框
function closeEdit() {
  visible.value = false;
}

//打开新增类目
const add = () => {
  imagesDrawer.value.open();
};
// 打开上传图片
const upload = () => {
  uploadDrawer.value.open();
};
</script>

<style lang="less" scoped>
html,
body {
  margin: 0;
  padding: 0;
}
ul {
  list-style: none;
  padding: 0;
}
.el-header,
.el-aside,
.el-main {
  // border: 1px solid gray;
  margin: 2px;
}
.el-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  p {
    width: 200px;
    height: 50px;
    // border: 1px solid deeppink;
    text-align: center;
    line-height: 50px;
  }
}
.el-aside {
  width: 200px;
  height: 78vh;
  .wrapper {
    position: relative;
    .pages {
      position: absolute;
      left: 0;
      top: 400px;
    }
    .item {
      display: flex;
      justify-content: space-between;
      border: 1px solid gray;
      border-radius: 25px;
      margin-top: 5px;
      &:hover {
        background: rgb(204, 229, 238);
      }
      span {
        display: flex;
        align-items: center;
        width: 90px;
        font-size: 12px;
        margin-left: 4px;
      }
      .btn > .el-button {
        border-radius: 25px;
      }
    }
  }
}
.active {
  background: rgb(204, 229, 238);
}

.el-main {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  align-items: flex-start;
  border: 1px solid gray;
  .imgs {
    width: 220px;
    height: 220px;
    margin: 10px;
    img {
      width: 100%;
      height: 100%;
    }
    p {
      font-size: 18px;
      width: 200px;
      height: 20px;
      line-height: 20px;
      padding: 0;
      text-align: center;
      // white-space: wrap;
    }
  }
}
.el-dialog {
  .nameBtn {
    display: flex;
    justify-content: center;
  }
}
</style>
